package com.quectel.cms.controller.sys;


import cn.hutool.core.lang.func.LambdaUtil;
import com.google.common.collect.Lists;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.util.SessionHolder;
import com.quectel.cms.vo.sys.SysMenuTreeDataVo;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.global.annotation.RequireTenants;
import com.quectel.constant.sys.SysConstants;
import com.quectel.sys.module.sys.dto.SysMenuDto;
import com.quectel.sys.module.sys.dto.SysRoleDto;
import com.quectel.sys.module.sys.service.SysMenuService;
import com.quectel.sys.module.sys.service.SysRoleService;
import com.quectel.sys.module.sys.service.SysUserService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 * @date 2019-04-02 09:42:45
 */
@RestController
@RequestMapping("sysMenu")
@Tag(name = "SysMenuController", description = "系统菜单相关api")
public class SysMenuController extends BaseController {

    @DubboReference
    private SysMenuService sysMenuService;

    @DubboReference
    private SysUserService sysUserService;

    @DubboReference
    private SysRoleService sysRoleService;

    /**
     * 当前登录用户可操作菜单
     */
    @GetMapping("currentUserMenuTree")
    @Operation(summary = "当前登录用户可操作菜单")
    public Response<List<SysMenuTreeDataVo>> currentUserMenuTree(@RequestParam Map<String, Object> params) {
        List<SysMenuDto> list = Lists.newArrayList();
        if (SysConstants.SYS_TOP_TENANT_CODE.equals(SessionHolder.getSysUser().getTenantCode()) &&
                SysConstants.SYS_TOP_GROUP_CODE.equals(SessionHolder.getSysUser().getGroupCode())) {
            //查询所有菜单
            params.put(LambdaUtil.getFieldName(SysMenuDto::getStatus), SystemConstants.YES.toString());
            list = sysMenuService.queryList(params);
        } else {
            Long userId = SessionHolder.getSysUserId();
            List<SysRoleDto> userRoleList = sysUserService.selectById(userId).getUserRoleList();

            for (SysRoleDto sysRoleDto : userRoleList) {
                List<SysMenuDto> roleMenuList = sysRoleService.selectById(sysRoleDto.getId()).getRoleMenuList();
                for (SysMenuDto sysMenuDto : roleMenuList) {
                    if (params.get("type") != null) {
                        if (!Byte.valueOf(params.get("type") + "").equals(sysMenuDto.getType())) {
                            continue;
                        }
                    }
                    if (sysMenuDto.isChecked()) {
                        if (CollectionUtils.isEmpty(
                                list.stream().filter(v -> Objects.equals(v.getId(), sysMenuDto.getId())).collect(Collectors.toList())
                        )) {
                            list.add(sysMenuDto);

                        }
                    }
                }
            }
        }

        return Response.<List<SysMenuTreeDataVo>>ok().wrap(treeBuilder(
                list.stream().
                        map(v->{
                            if (SystemConstants.YES.equals(v.getIsSystemLevel())) {
                                v.setName(v.getName() + "(" + "系统级" + ")");
                            }
                            return v;
                        }).
                        collect(Collectors.toList())
        ));
    }

    /**
     * 获取系统所有菜单
     *
     * @param params
     * @return
     */
    @GetMapping("menuTree")
    @Operation(summary = "获取系统所有菜单")
    @RequireTenants(values = SysConstants.SYS_TOP_TENANT_CODE)
    public Response<List<SysMenuTreeDataVo>> menuTree(@RequestParam Map<String, Object> params) {
        List<SysMenuDto> list = sysMenuService.queryList(params);
        return Response.<List<SysMenuTreeDataVo>>ok().wrap(treeBuilder(list));
    }

    private List<SysMenuTreeDataVo> treeBuilder(List<SysMenuDto> list) {


        List<SysMenuTreeDataVo> groups = new ArrayList<>();

        List<SysMenuTreeDataVo> SysMenuTreeDataVos = CopyUtils.copyList(list, SysMenuTreeDataVo.class);
        for (SysMenuTreeDataVo c1 : SysMenuTreeDataVos) {
            if (list.parallelStream().noneMatch(o -> o.getId().equals(c1.getParentId()))) {
                // 没匹配到就是最顶级节点
                groups.add(c1);
            }
            for (SysMenuTreeDataVo c2 : SysMenuTreeDataVos) {
                if (c2.getParentId().equals(c1.getId())) {
                    if (c1.getChildes() == null) {
                        c1.setChildes(new ArrayList<>());
                    }
                    c2.setParentName(c1.getName());
                    c1.getChildes().add(c2);
                }
            }
        }
        return groups;
    }

    /**
     * 根据id查询系统菜单记录
     */
    @GetMapping("info/{id}")
    @RequirePermissions(values = "sysMenu:info")
    @Operation(summary = "根据id查询系统菜单记录")
    public Response<SysMenuDto> info(@PathVariable("id") Long id) {
        SysMenuDto sysMenuDto = sysMenuService.selectById(id);

        return Response.<SysMenuDto>ok().wrap(sysMenuDto);
    }

    /**
     * 保存系统菜单记录
     */
    @PostMapping("save")
    @RequirePermissions(values = "sysMenu:edit")
    @Operation(summary = "保存系统菜单记录")
    public Response<Object> save(@RequestBody @Validated SysMenuDto sysMenuDto) {
        sysMenuService.save(sysMenuDto);
        return Response.ok();
    }

    /**
     * 修改系统菜单记录
     */
    @PostMapping("update")
    @RequirePermissions(values = "sysMenu:edit")
    @Operation(summary = "修改系统菜单记录")
    public Response<Object> update(@RequestBody @Validated SysMenuDto sysMenuDto) {
        sysMenuService.updateById(sysMenuDto);
        return Response.ok();
    }

    /**
     * 删除系统菜单记录
     */
    @PostMapping("delete")
    @RequirePermissions(values = "sysMenu:delete")
    @Operation(summary = "删除系统菜单记录")
    public Response<Object> delete(@RequestBody Long[] ids) {
        String message = sysMenuService.deleteBatch(ids);
        return message != null ? Response.error(message) : Response.ok();
    }
}
